// pages/login/login.js
// var app =  getApp();
import { showModal, showToast, uploadFile, chooseImage, showLoading } from "../../util/AsyncWx.js";
import { request, request1 } from "../../request/index.js";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: {
      nickname: '',
      avatarurl: '',
      openid: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    var that = this
    wx.login({
      timeout: 10000,
      success: (result) => {
        var code = result.code
        var openid = 'user.openid';
        wx.request({
          url: 'http://localhost:8080/getopenid',
          data: { code: code },
          header: { 'content-type': 'application/json' },
          method: 'GET',
          dataType: 'json',
          responseType: 'text',
          success: (res) => {
            this.setData({
              [openid]: res.data.openid
            })
          }
        });
      }
    });
  },
  async handleGetUserInfo(e) {
    var that = this;
    if (that.data.user.openid == '') {
      showToast({ title: "系统繁忙，请稍后登录" })
    } else {
      var openid = that.data.user.openid
      const { userInfo } = e.detail;
      var nickname = 'user.nickname';
      var avatarurl = 'user.avatarurl';
      that.setData({
        [nickname]: e.detail.userInfo.nickName,
        [avatarurl]: e.detail.userInfo.avatarUrl
      })
      var user = that.data.user;
      const result = await request({ url: "/user/selectByOpenId", data: { openid } })
      if (result.length !== 0) {
        var newNickName = that.data.user.nickname
        var oldNickName = result[0].nickname
        var newAvatarurl = that.data.user.avatarurl
        var oldAvatarurl = result[0].avatarurl
        var userinfo = result[0]
        if (newNickName == oldNickName && newAvatarurl == oldAvatarurl) {
          wx.setStorageSync("userInfo", result[0]);
          wx.switchTab({
            url: '/pages/index/index',
          });
        } else {
          const result = await request({ url: "/user/updataUserInfo", method: "POST", data: user });
          wx.setStorageSync("userInfo", result[0]);
          wx.switchTab({
            url: '/pages/index/index',
          });
        }
      } else {
        const res1 = await request({ url: "/user/insertUser", method: "POST", data: user })
        wx.setStorageSync("userInfo", user);
        wx.switchTab({
          url: '/pages/index/index',
        });

      }

    }

  },

})









